package com.test.demo.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.test.demo.commons.ResponseResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传
 *
 * @author 远 chards_
 * @date: 2020-02-19 23:23
 */
@CrossOrigin(origins = "*", maxAge = 3600,allowCredentials = "true")
@RestController
@RequestMapping("upload")
public class UploadController {

    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI4FwnTpUo7ghiEa4B2baL";
    private static final String ACCESS_KEY_SECRET = "HCGynKpl9OL0fe0oFFYHxfpYBtlz45";
    private static final String BUCKET_NAME = "chards";
    /**
     * 文件上传
     *
     * @param multipartFile @{code MultipartFile}
     * @return {@link ResponseResult<  >} 文件上传路径
     */
    @PostMapping(value = "")
    public ResponseResult<String> upload(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //设置文件名
        String newName = fileName+ "." + suffix;

        OSS client = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            client.putObject(new PutObjectRequest(BUCKET_NAME, newName, multipartFile.getInputStream()));
            // 上传文件路径 = http://BUCKET_NAME.ENDPOINT/自定义路径/fileName
            return new ResponseResult<String>(ResponseResult.CodeStatus.OK, "文件上传成功", "http://" + BUCKET_NAME + "." + ENDPOINT + "/" + newName);
        } catch (IOException e) {
            return new ResponseResult<String>(ResponseResult.CodeStatus.FAIL, "文件上传失败，请重试",null);
        } finally {
            client.shutdown();
        }
    }
}
